﻿using AppSocketModel;
using AppSocketService.Account;
using AppSocketService.Vehicle;
using BCGPSCommon;
using BCGPSMongoData;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AppSocketService.HistoryLocation
{
    /// <summary>
    /// GPS历史轨迹
    /// </summary>
    public class HistoryLocationService :ServiceBase, IHistoryLocationService
    {
        #region var
        private readonly MongoDBCommand<GpsInfoDto> mongoDBCommand = new MongoDBCommand<GpsInfoDto>("HistoryGpsData");
        private readonly AccountDto CurrentAccount;
        private readonly IVehicleService vehicleService;
        private readonly GCJ02_WGS84_TransTools gCJ02_WGS84_TransTools = new GCJ02_WGS84_TransTools();
        #endregion
        public HistoryLocationService(IClaimsAccessor claimsAccesso,  IAccountService accountService, ISystemAccountService systemAccountService, IVehicleService vehicleService) : base(claimsAccesso)
        {
            if (claimsAccesso.AccountRole == AccountRole.SYSTEM)
                CurrentAccount = systemAccountService.GetCurrentAccount().AsAccountDto();
            else
                CurrentAccount = accountService.GetCurrentAccount(); 
            this.vehicleService = vehicleService;
        }
         
        #region 查询GPS历史记录
        public PageableList<GpsInfoDto> QueryByImei(GpsMapType gpsMapType, string imei, DateTime start, DateTime end, bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0;
            if (end.Hour == 0 && end.Minute == 0 && end.Second == 0)
                end = end.AddDays(1);
            start = MongoDBDateTime.GetUtc(start);
            end = MongoDBDateTime.GetUtc(end);
            var page = mongoDBCommand.SelectDocumentsAsync(s => s.Imei == imei && s.GpsTime >= start && s.ServerTime < end, s => s.CreateTime, desc, index*size, size).GetAwaiter().GetResult();

            if (page.Items != null)
            {
                foreach (var item in page.Items)
                {
                    LocateInfo info;
                    switch (gpsMapType)
                    {
                        case GpsMapType.GDMAP:
                            info = gCJ02_WGS84_TransTools.wgs84_To_Gcj02(item.Lat, item.Lng);
                            item.Lat = info.Latitude;
                            item.Lng = info.longitude;
                            break;
                        case GpsMapType.BAIDUMAP:
                            info = gCJ02_WGS84_TransTools.wgs84_To_Bd09(item.Lat, item.Lng);
                            item.Lat = info.Latitude;
                            item.Lng = info.longitude;
                            break;
                    }
                }
            }
            return page;
        }
        #endregion

    }
}
